# coding=utf-8

# 记录最近一次测试结果

from copy import deepcopy

from app.extensions import session_id_manager


class LastResult:
    LastResultPool = {}

    @classmethod
    def get_last_result(cls) -> dict:
        session_id = session_id_manager.get_session_id()
        return cls.LastResultPool.get(session_id)

    @classmethod
    def update_last_result(cls, result, request_headers, request_body, response_headers, response_body):
        """更新所有字段"""
        cls._check_current_session_id_last_result_exist()
        session_id = session_id_manager.get_session_id()
        cls.LastResultPool.get(session_id).update({
            'result': deepcopy(result),
            'request_headers': deepcopy(request_headers),
            'request_body': deepcopy(request_body),
            'response_headers': deepcopy(response_headers),
            'response_body': deepcopy(response_body),
        })

    @classmethod
    def update_request_and_response_to_last_result(cls, request_headers, request_body, response_headers, response_body):
        """更新请求和应答数据"""
        cls._check_current_session_id_last_result_exist()
        session_id = session_id_manager.get_session_id()
        cls.LastResultPool.get(session_id).update({
            'request_headers': deepcopy(request_headers),
            'request_body': deepcopy(request_body),
            'response_headers': deepcopy(response_headers),
            'response_body': deepcopy(response_body),
        })

    @classmethod
    def update_result_to_last_result(cls, result):
        """更新最近一次执行结果"""
        cls._check_current_session_id_last_result_exist()
        session_id = session_id_manager.get_session_id()
        cls.LastResultPool.get(session_id).update({
            'result': deepcopy(result),
        })

    @classmethod
    def _check_current_session_id_last_result_exist(cls):
        """检查当前session_id是否在LastResultPool中，如果没有则新增一个空字典"""
        session_id = session_id_manager.get_session_id()
        if session_id not in cls.LastResultPool:
            cls.LastResultPool.update({
                session_id: {
                    'result': None,             # 上次执行结果
                    'request_headers': None,    # 请求头
                    'request_body': None,       # 请求包
                    'response_headers': None,   # 应答头
                    'response_body': None,      # 应答包
                }
            })

